package cn.zhj.base.app

import android.util.Log.VERBOSE
import cn.zhj.mvpart.integration.IRepositoryManager
import com.ihsanbal.logging.Level
import com.ihsanbal.logging.LoggingInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object BaseApi : IRepositoryManager {

    val BASE_URL = "http://www.baidu.com/"

    private var mOkHttpClient: OkHttpClient? = null

    override fun <T> obtainRetrofitService(service: Class<T>): T {
        return createApi(service)
    }

    private fun <T> createApi(clazz: Class<T>):T {
        return createApi(clazz , BASE_URL)
    }

    private fun <T> createApi(clazz: Class<T>, baseUrl: String):T = Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .client(provideClient())
        .build()
        .create(clazz)

    private fun provideClient(): OkHttpClient? {
        if(mOkHttpClient != null){
            return mOkHttpClient
        }

        mOkHttpClient = OkHttpClient.Builder()
            .connectTimeout(3 , TimeUnit.SECONDS)
            .readTimeout(3 , TimeUnit.SECONDS)
            .addInterceptor(loggingInterceptor)
            .addInterceptor(headerInterceptor)
            //.proxy(Proxy.NO_PROXY)
            .build()
        return mOkHttpClient
    }

    /**
     * 日志拦截器https://github.com/ihsanbal/LoggingInterceptor
     */
    private val loggingInterceptor = LoggingInterceptor.Builder()
        .setLevel(Level.BASIC)
        .log(VERBOSE)
        .build()

    /**
     * 请求头拦截器
     */
    private val headerInterceptor  = Interceptor {
        var request = it.request()
            .newBuilder()
            .addHeader("runPlatform" , "android")
            .build()
        it.proceed(request)
    }


}
